rm(list=ls())
gc()
## SURVEY RESULT TABLES
library(modelsummary)
library(dplyr)
library(tidyr)
library(stringr)
library(tibble)
library(readr)
library(gt)
library(data.table)
library(gt)
#gc()

load('results/survey-results-no-weights-alt.Rdata')
load('results/survey-results-weights-alt.Rdata')


source('felm-summary-table.R')



vars = c('Dem Exp', 'HH Dem',  'Dem Exp * Dem','HH Dem * Dem', 'Rep Exp', 'HH Rep' ,'Rep Exp * Rep', 'HH Rep * Rep')
names(vars)= c('DemSpExp_nohh_alt', 'hh.d.adj','DemSpExp_nohh_alt:Democrat','hh.d.adj:Democrat','RepSpExp_nohh_alt','hh.r.adj', 'RepSpExp_nohh_alt:Republican','hh.r.adj:Republican')
l = list(w1DemSpExp, m1DemSpExp,
         w1RepSpExp, m1RepSpExp,
         w2DemSpExp, m2DemSpExp,
         w2RepSpExp, m2RepSpExp,
         w5DemSpExp, m5DemSpExp,
         w5RepSpExp, m5RepSpExp)
names(l) = c('(1)', '(2)','(3)', '(4)', '(5)', '(6)', '(7)', '(8)','(9)', '(10)', '(11)', '(12)')
tab1 = felm.summary.table(summaries = l,
                          coef_map = vars, output ='gt',
                          model.names=names(l), fmt =3,
                          add_rows = data.frame(v1 = 'Weighted',
                                                v2 = 'Yes',
                                                v3 = 'No',
                                                v4 = 'Yes',
                                                v5 = 'No',
                                                v6 = 'Yes',
                                                v7 = 'No',
                                                v8 = 'Yes',
                                                v9 = 'No',
                                                v10 = 'Yes',
                                                v11 = 'No',
                                                v12 = 'Yes',
                                                v13 = 'No'))

tab1 %>%
  
  # column labels
  tab_spanner(label = 'Neighbors: Democrats or Republicans', columns = 2:5) %>%
  tab_spanner(label = 'Contact: Democrats', columns = 6:7) %>%
  tab_spanner(label = 'Contact: Republicans', columns = 8:9) %>%
  tab_spanner(label = 'Comfort: Neighbors know Party', columns = 10:13) %>%
  
  
  as_latex()%>%
  as.character %>%
  str_replace_all('longtable','tabular')%>%
  write_file('tables/TabS20.tex')



